//
//  ZNWBOAuthViewController.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/10.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZNWBOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()

    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "登录新浪微博"
        
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(dismissSelf), event: .touchUpInside, isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill), event: .touchUpInside)
        
        //OAuth2 授权：
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(ZNWBClientID)&redirect_uri=\(ZNWBRedirectURI)"
        guard let url = URL(string: urlString) else {
            print("invalid url")
            
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.scrollView.isScrollEnabled = false
        webView.loadRequest(request)
        webView.delegate = self
    }
    
    @objc func dismissSelf() {
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc func autoFill() {
        //Webview 注入：直接通过js修改本地浏览器中的网页缓存，然后执行submit，将数据提交到服务器
        let js = "document.getElementById('userId').value = '18328018691';" + "document.getElementById('passwd').value = 'evelasting/520';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension ZNWBOAuthViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //此处需要获取授权成功后的授权码，通过URL前缀判断是否已经进入百度。没有进入则继续请求
        if request.url?.absoluteString.hasPrefix(ZNWBRedirectURI) == false {
            return true
        }
        
        //url的组成：协议头、主机名、资源路径
        //query：GET请求的参数，即?后面的全部内容
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("用户取消授权")
            
            dismissSelf()
            
            return false
        }
        
        //取出授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print(code)
        
        // completion:处理登录回调
        ZNWBNetworkManager.shared.loadOAuthAccessToken(code: code) { (success) in
            if success {                
                // 发出登录成功的通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZNWBLoginSuccessNotification), object: nil)
                
                self.dismissSelf()
            } else {
                SVProgressHUD.showError(withStatus: "获取访问令牌失败")
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
